package io.iec.edp.caf.msu.common;

import io.iec.edp.caf.datasource.CAFDataSourceSelector;
import io.iec.edp.caf.msu.api.ServiceUnitAwareService;
import io.iec.edp.caf.msu.api.client.ServiceDiscovery;
import io.iec.edp.caf.msu.api.entity.GspAppServerInstance;
import io.iec.edp.caf.msu.api.entity.GspSuInstance;
import io.iec.edp.caf.msu.common.domain.converter.GspAppConverter;
import io.iec.edp.caf.msu.common.domain.converter.GspSuConverter;
import io.iec.edp.caf.msu.common.domain.entity.GspAppServerEntity;
import io.iec.edp.caf.msu.common.domain.repository.AppServerRepository;
import io.iec.edp.caf.msu.common.domain.repository.SuRepository;

import java.util.ArrayList;
import java.util.List;

/**
 * Database下MsuServiceImpl的方法{getGspAppServerInfoBySu}和{getGspSuInfo}方法会返回数据，为避免出现兼容问题，故在此做实现。派生自MsuServiceImpl
 *
 * @date 2024-04-17
 */
public class DBMsuServiceImpl extends MsuServiceImpl {

    private AppServerRepository appRepo;

    private SuRepository suRepo;

    public DBMsuServiceImpl(ServiceUnitAwareService suAware, ServiceDiscovery serviceDiscovery, AppServerRepository appRepo, SuRepository suRepo) {
        super(suAware, serviceDiscovery);

        this.appRepo = appRepo;
        this.suRepo = suRepo;
    }

    //根据Su名称获取appServer信息
    public List<GspAppServerInstance> getGspAppServerInfoBySu(String suName) {
        try {
            CAFDataSourceSelector.selectMaster();

            List<GspAppServerEntity> apps = this.appRepo.findBySuName(suName.toLowerCase());
            if (apps == null || apps.size() == 0) {
                apps = this.appRepo.findBySuName(suName);
            }

            List<GspAppServerInstance> instances = new ArrayList<>();
            if (apps != null && apps.size() > 0) {
                for (GspAppServerEntity entity : apps) {
                    instances.add(GspAppConverter.convertToInstance(entity));
                }
            }

            return instances;
        } finally {
            CAFDataSourceSelector.reset();
        }
    }

    //获取一个Su的信息
    public GspSuInstance getGspSuInfo(String suName) {
        try {
            CAFDataSourceSelector.selectMaster();

            return GspSuConverter.convertToInstance(this.suRepo.findById(suName).get());
        } finally {
            CAFDataSourceSelector.reset();
        }
    }

}
